package com.uduemc.biso.node.web.service.html.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.SysComponentType;
import com.uduemc.biso.core.extities.center.SysContainerType;
import com.uduemc.biso.node.core.common.entities.SiteComponent;
import com.uduemc.biso.node.core.common.entities.SiteComponentSimple;
import com.uduemc.biso.node.core.common.entities.SiteContainer;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SComponent;
import com.uduemc.biso.node.core.entities.SComponentQuoteSystem;
import com.uduemc.biso.node.core.entities.SContainer;
import com.uduemc.biso.node.core.entities.SContainerQuoteForm;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.web.component.HIComponentUdinComponent;
import com.uduemc.biso.node.web.component.HIContainerUdinComponent;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.html.inter.HIComponentSimpleUdin;
import com.uduemc.biso.node.web.component.html.inter.HIComponentUdin;
import com.uduemc.biso.node.web.component.html.inter.HIContainerUdin;
import com.uduemc.biso.node.web.component.html.inter.HISystemComponentUdin;
import com.uduemc.biso.node.web.service.ContentService;
import com.uduemc.biso.node.web.service.SRHeadService;
import com.uduemc.biso.node.web.service.byfeign.CategoryService;
import com.uduemc.biso.node.web.service.byfeign.ComponentService;
import com.uduemc.biso.node.web.service.byfeign.ContainerService;
import com.uduemc.biso.node.web.service.byfeign.PageService;
import com.uduemc.biso.node.web.service.byfeign.SysStaticDataService;
import com.uduemc.biso.node.web.service.byfeign.SystemService;
import com.uduemc.biso.node.web.service.html.BasicUdinService;
import com.uduemc.biso.node.web.service.html.HFooterService;
import com.uduemc.biso.node.web.service.html.HFormService;
import com.uduemc.biso.node.web.utils.AssetsResponseUtil;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

@Service
public class HFooterServiceImpl implements BasicUdinService, HFooterService {
	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private ComponentService componentServiceImpl;

	@Autowired
	private SysStaticDataService sysStaticDataServiceImpl;

	@Autowired
	private HIContainerUdinComponent hIContainerUdinComponent;

	@Autowired
	private HIComponentUdinComponent hIComponentUdinComponent;

	@Autowired
	private SRHeadService sRHeadServiceImpl;

	@Autowired
	private PageService pageServiceImpl;

	@Autowired
	private HFormService hFormServiceImpl;

	@Autowired
	private SystemService systemServiceImpl;

	@Autowired
	private ContentService contentServiceImpl;

	@Autowired
	private ContainerService containerServiceImpl;

	@Autowired
	private CategoryService categoryServiceImpl;

	@Override
	public StringBuilder html() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		// 获取当前页面的所有容器数据以及组件数据
		long hostId = requestHolder.getHostId();
		long siteId = requestHolder.getSiteId();

		// footer 区域组件内容区域HTML渲染内容以及简易组件HTML渲染内容
		return html(hostId, siteId);
	}

	@Override
	public StringBuilder html(long hostId, long siteId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		// footer 区域组件内容区域HTML渲染内容
		List<SiteContainer> listSiteContainer = containerServiceImpl.getInfosByHostSitePageIdAndArea(hostId, siteId, 0, (short) 1);

		if (CollectionUtils.isEmpty(listSiteContainer)) {
			return new StringBuilder("<!-- footer empty -->");
		}

		List<SiteContainerParentData> listSiteContainerParentData = SiteContainerParentData.getListSiteContainerParentData(listSiteContainer);
		List<SiteComponent> listSiteComponent = componentServiceImpl.getInfosByHostSitePageIdAndArea(hostId, siteId, 0, (short) 1);

		// 过滤富文本中的内容
		if (!CollectionUtils.isEmpty(listSiteComponent)) {
			for (SiteComponent siteComponent : listSiteComponent) {
				SComponent component = siteComponent.getComponent();
				String content = component.getContent();
				component.setContent(contentServiceImpl.filterUEditorContentWithSite(content));
			}
		}

		// 容器引用表单数据获取
		List<SContainerQuoteForm> listSContainerQuoteForm = containerServiceImpl.getSContainerQuoteFormOkByHostSiteId(hostId, siteId);

		StringBuilder stringBuilder = new StringBuilder("<!-- footer -->\n");

		// footer 区域组件内容区域HTML渲染内容结果
		List<StringBuilder> makeHtmlComponent = makeHtmlComponent(listSiteContainerParentData, listSiteComponent, listSContainerQuoteForm, 0L);

		if (!CollectionUtils.isEmpty(makeHtmlComponent)) {
			makeHtmlComponent.forEach(stringBuilder::append);
		}

		// 简易组件HTML渲染内容
		List<SiteComponentSimple> listSiteComponentSimple = new ArrayList<>();

		List<SiteComponentSimple> hostSiteComponentSimple = componentServiceImpl.getComponentSimpleInfo(hostId, 0L, (short) 0,
				"`s_component_simple`.`type_id` ASC");
		if (!CollectionUtils.isEmpty(hostSiteComponentSimple)) {
			listSiteComponentSimple.addAll(hostSiteComponentSimple);
		}
		List<SiteComponentSimple> siteSiteComponentSimple = componentServiceImpl.getComponentSimpleInfo(hostId, siteId, (short) 0,
				"`s_component_simple`.`type_id` ASC");
		if (!CollectionUtils.isEmpty(siteSiteComponentSimple)) {
			listSiteComponentSimple.addAll(siteSiteComponentSimple);
		}

		// 简易组件HTML渲染内容结果
		List<StringBuilder> makerHtmlComponentSimple = makerHtmlComponentSimple(listSiteComponentSimple);

		if (!CollectionUtils.isEmpty(makerHtmlComponentSimple)) {
			makerHtmlComponentSimple.forEach(item -> {
				stringBuilder.append(item);
			});
		}

		stringBuilder.append("\n<div id=\"component-menufootfixed-render\"></div>");

		return AssetsResponseUtil.htmlCompress(stringBuilder);
	}

	private List<StringBuilder> makerHtmlComponentSimple(List<SiteComponentSimple> listSiteComponentSimple) {
		if (CollectionUtils.isEmpty(listSiteComponentSimple)) {
			return null;
		}
		List<StringBuilder> arrayList = new ArrayList<>();
		Iterator<SiteComponentSimple> iterator = listSiteComponentSimple.iterator();
		while (iterator.hasNext()) {
			SiteComponentSimple siteComponentSimple = iterator.next();
			SysComponentType componentType = siteComponentSimple.getComponentType();

			HIComponentSimpleUdin hIComponentSimpleUdin = hIComponentUdinComponent.getHIComponentSimpleUdinByName(componentType.getType());
			StringBuilder html = hIComponentSimpleUdin.html(siteComponentSimple);
			arrayList.add(html);
		}
		return arrayList;
	}

	private List<StringBuilder> makeHtmlComponent(List<SiteContainerParentData> listSiteContainerParentData, List<SiteComponent> listSiteComponent,
			List<SContainerQuoteForm> listSContainerQuoteForm, long parentId)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		List<SiteContainer> listSiteContainer = getChildrenData(listSiteContainerParentData, parentId);
		if (CollectionUtils.isEmpty(listSiteContainer)) {
			if (parentId < 1) {
				return null;
			}
			// 容器引用表单数据
			SiteContainer siteContainer = null;
			Iterator<SiteContainerParentData> iterator = listSiteContainerParentData.iterator();
			while (iterator.hasNext()) {
				SiteContainerParentData next = iterator.next();
				Iterator<SiteContainer> iteratorSiteContainer = next.getData().iterator();
				while (iteratorSiteContainer.hasNext()) {
					SiteContainer nextSiteContainer = iteratorSiteContainer.next();
					if (nextSiteContainer.getSContainer().getId().longValue() == parentId) {
						siteContainer = nextSiteContainer;
					}
				}
			}
			if (siteContainer == null || siteContainer.getSContainer().getId() == null || siteContainer.getSContainer().getBoxId() == null) {
				return null;
			}

			SiteComponent siteComponent = getChildrenData(parentId, listSiteContainerParentData, listSiteComponent);
			if (siteComponent != null) {
				// 获取 component 的HTML渲染内容
				SysComponentType componentType = null;
				try {
					componentType = sysStaticDataServiceImpl.getComponentTypeInfoById(siteComponent.getComponent().getTypeId());
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (componentType != null) {
					if (componentType.getCateType() != null && componentType.getCateType().shortValue() == (short) 2) {
						HISystemComponentUdin systemComponentUdin = hIComponentUdinComponent.getHISystemComponentUdinByName(componentType.getType());
						if (systemComponentUdin != null) {
							// 获取 SPage、SSystem 数据
							SComponentQuoteSystem quoteSystem = siteComponent.getQuoteSystem();
							if (quoteSystem == null) {
								return null;
							}
							Long quotePageId = quoteSystem.getQuotePageId();
							Long quoteSystemId = quoteSystem.getQuoteSystemId();
							Long quoteSystemCategoryId = quoteSystem.getQuoteSystemCategoryId();

							SPage page = pageServiceImpl.getPageByHostPageId(siteComponent.getComponent().getHostId(), quotePageId);
							SSystem system = systemServiceImpl.findInfo(siteComponent.getComponent().getHostId(), quoteSystemId);
							SCategories categories = null;
							if (quoteSystemCategoryId != null && quoteSystemCategoryId.longValue() > 0) {
								categories = categoryServiceImpl.getInfoByHostCategoryId(siteComponent.getComponent().getHostId(), quoteSystemId,
										quoteSystemCategoryId);
							}

							List<StringBuilder> arrayList = new ArrayList<StringBuilder>();
							arrayList.add(systemComponentUdin.html(page, system, categories, siteComponent));
							return arrayList;
						}
					} else {
						HIComponentUdin componentUdin = hIComponentUdinComponent.getHIComponentUdinByName(componentType.getType());
						if (componentUdin != null) {
							List<StringBuilder> arrayList = new ArrayList<StringBuilder>();
							arrayList.add(componentUdin.html(siteComponent));
							return arrayList;
						}
					}
				}
			}

			SContainerQuoteForm sContainerQuoteForm = getFormChildrenData(siteContainer, listSContainerQuoteForm);
			if (sContainerQuoteForm != null) {
				sRHeadServiceImpl.remakeform();
				StringBuilder html = hFormServiceImpl.html(sContainerQuoteForm);
				List<StringBuilder> arrayList = new ArrayList<StringBuilder>();
				arrayList.add(html);
				return arrayList;
			}
			return null;
		}

		List<StringBuilder> arrayList = new ArrayList<StringBuilder>();
		listSiteContainer.forEach(item -> {
			StringBuilder stringBuilder = new StringBuilder();
			Long id = item.getSContainer().getId();
			// 子节点的所有渲染html内容
			List<StringBuilder> makeHtml = null;
			try {
				makeHtml = makeHtmlComponent(listSiteContainerParentData, listSiteComponent, listSContainerQuoteForm, id);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			SContainer sContainer = item.getSContainer();
			Long typeId = sContainer.getTypeId();
			SysContainerType sysContainerType = null;
			try {
				sysContainerType = sysStaticDataServiceImpl.getContainerTypeInfoById(typeId);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (sysContainerType != null) {
				HIContainerUdin containerUdin = hIContainerUdinComponent.getHIContainerUdinByName(sysContainerType.getType());
				if (containerUdin != null) {
					StringBuilder html = containerUdin.html(item, makeHtml);
					stringBuilder.append(html);
				}
			}
			arrayList.add(stringBuilder);
		});

		return arrayList;
	}

	private static SiteComponent getChildrenData(long scontainerId, List<SiteContainerParentData> listSiteContainerParentData,
			List<SiteComponent> listSiteComponent) {
		if (CollectionUtils.isEmpty(listSiteComponent)) {
			return null;
		}
		SiteContainer siteContainer = null;
		Iterator<SiteContainerParentData> iterator = listSiteContainerParentData.iterator();
		while (iterator.hasNext()) {
			SiteContainerParentData next = iterator.next();
			Iterator<SiteContainer> iteratorSiteContainer = next.getData().iterator();
			while (iteratorSiteContainer.hasNext()) {
				SiteContainer nextSiteContainer = iteratorSiteContainer.next();
				if (nextSiteContainer.getSContainer().getId().longValue() == scontainerId) {
					siteContainer = nextSiteContainer;
				}
			}
		}
		if (siteContainer == null || siteContainer.getSContainer().getId() == null || siteContainer.getSContainer().getBoxId() == null) {
			return null;
		}
		Iterator<SiteComponent> iteratorSiteComponent = listSiteComponent.iterator();
		while (iteratorSiteComponent.hasNext()) {
			SiteComponent siteComponent = iteratorSiteComponent.next();
			Long containerId = siteComponent.getComponent().getContainerId();
			Long containerBoxId = siteComponent.getComponent().getContainerBoxId();
			if (containerId == null || containerBoxId == null) {
				return null;
			}

			if (siteContainer.getSContainer().getId().longValue() == containerId.longValue()
					&& siteContainer.getSContainer().getBoxId().longValue() == containerBoxId.longValue()) {
				return siteComponent;
			}
		}
		return null;
	}

	private static List<SiteContainer> getChildrenData(List<SiteContainerParentData> listSiteContainerParentData, long parentId) {
		List<SiteContainer> listSiteContainer = null;
		Iterator<SiteContainerParentData> iterator = listSiteContainerParentData.iterator();
		while (iterator.hasNext()) {
			SiteContainerParentData siteContainerParentData = iterator.next();
			if (siteContainerParentData.getParentId() == parentId) {
				listSiteContainer = siteContainerParentData.getData();
			}
		}
		return listSiteContainer;
	}

	/**
	 * 通过 参数 验证并且获取 List<SContainerQuoteForm> listSContainerQuoteForm 数据列表中对应的
	 * SContainerQuoteForm 数据
	 * 
	 * @param scontainerId
	 * @param listSiteContainerParentData
	 * @param listSContainerQuoteForm
	 * @return
	 */
	private static SContainerQuoteForm getFormChildrenData(SiteContainer siteContainer, List<SContainerQuoteForm> listSContainerQuoteForm) {
		if (CollectionUtils.isEmpty(listSContainerQuoteForm)) {
			return null;
		}
		Iterator<SContainerQuoteForm> iteratorSContainerQuoteForm = listSContainerQuoteForm.iterator();
		while (iteratorSContainerQuoteForm.hasNext()) {
			SContainerQuoteForm sContainerQuoteForm = iteratorSContainerQuoteForm.next();
			if (sContainerQuoteForm.getContainerId().longValue() == siteContainer.getSContainer().getId().longValue()) {
				return sContainerQuoteForm;
			}
		}
		return null;
	}

	@Data
	@Accessors(chain = true)
	@ToString
	public static class SiteContainerParentData {
		private long parentId;
		private List<SiteContainer> data;

		public static List<SiteContainerParentData> getListSiteContainerParentData(List<SiteContainer> listSiteContainer) {
			if (CollectionUtils.isEmpty(listSiteContainer)) {
				return null;
			}
			List<SiteContainerParentData> listSiteContainerParentData = new ArrayList<HFooterServiceImpl.SiteContainerParentData>();

			Iterator<SiteContainer> iterator = listSiteContainer.iterator();
			while (iterator.hasNext()) {
				SiteContainer next = iterator.next();
				long parentId = next.getSContainer().getParentId() == null ? 0 : next.getSContainer().getParentId().longValue();

				// 是否存在
				SiteContainerParentData item = null;
				Iterator<SiteContainerParentData> iteratorSiteContainerParentData = listSiteContainerParentData.iterator();
				while (iteratorSiteContainerParentData.hasNext()) {
					SiteContainerParentData siteContainerParentData = iteratorSiteContainerParentData.next();
					if (siteContainerParentData.getParentId() == parentId) {
						item = siteContainerParentData;
						break;
					}
				}

				if (item == null) {
					item = new SiteContainerParentData();
					item.setParentId(parentId);
					item.setData(new ArrayList<>());
					listSiteContainerParentData.add(item);
				}

				item.getData().add(next);
			}

			return listSiteContainerParentData;
		}
	}

}
